package org.microdream.easy.deploy.action;

import com.alibaba.fastjson.JSONArray;
import ice.server.comm.GloubCode;
import ice.server.comm.ParamBulider;
import ice.tool.ResultMap;
import ice.tool.bean.BeanUtil;
import org.apache.commons.lang3.StringUtils;
import org.microdream.easy.deploy.po.DRent;
import org.microdream.easy.deploy.service.DRentService;
import org.microdream.easy.deploy.service.DSequenceService;
import org.microdream.easy.deploy.utils.ListUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/DRent")
public class DRentAction {

    @Resource
    private DRentService dRentService;
    @Resource
    private DSequenceService dSequenceService;

    @PostMapping("/searchByPage")
    public Map searchByPage(Integer limit, Integer offset){
        if(limit==null || offset==null){
            return null;
        }
        return dRentService.searchByPage(ParamBulider.build().addEqual("rows", limit).addEqual("page", offset / limit).addEqual("isDelete",0).get());
    }

    @PostMapping("")
    public Map add(DRent dRent){
        dRent.setRentCode(dSequenceService.getNextSequence(GloubCode.RENTCODE.getName(),GloubCode.SUPPLEMENTCODE.getName()));
        dRent.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        dRent.setIsDelete(0);
        dRent.setIslock(0);
        return dRentService.add(dRent);
    }

    @PutMapping("")
    public Map update(DRent dRent){
        DRent dRentOld = dRentService.get(dRent.getId());
        try {
            BeanUtil.copyNotEmptyProprties(dRent,dRentOld);
            dRentOld.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        } catch (Exception e) {
            return ResultMap.build().warningState().message(e.getMessage()).get();
        }
        return dRentService.upd(dRentOld);
    }

    @DeleteMapping("/{key}")
    public Map delete(@PathVariable("key")String key){
        if(StringUtils.isEmpty(key)){
            return ResultMap.build().warningState().message("无效数据").get();
        }
        List<String> ids = Arrays.asList(key.split(","));
        return dRentService.del(ListUtil.StringToInteger(ids));
    }

    @GetMapping("/{key}")
    public DRent searchById(@PathVariable("key") Integer key){
        return dRentService.get(key);
    }

    @GetMapping("lock/{key}")
    public Map lock(@PathVariable("key") Integer key){
        return dRentService.lock(key);
    }

    /**
     * select组件选择租户的接口
     * @return
     */
    @GetMapping("/forSelect")
    public List<DRent> getRentForSelect() {
    	return dRentService.find(ParamBulider.build().get());
    }

    @GetMapping("/getRentKeyValue")
    public JSONArray getRentKeyValue(){
        return dRentService.getRentKeyValue("","");
    }
}
